package com.liufujie.baidumapdemo.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.busline.BusLineResult;
import com.baidu.mapapi.search.busline.BusLineSearch;
import com.baidu.mapapi.search.busline.BusLineSearchOption;
import com.baidu.mapapi.search.busline.OnGetBusLineSearchResultListener;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.liufujie.baidumapdemo.R;
import com.liufujie.baidumapdemo.mapapi.overlayutil.BusLineOverlay;
import com.liufujie.baidumapdemo.mapapi.overlayutil.PoiOverlay;

public class PoiSearchActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btnAddr, btnBus;

    //标志位 判断是否点击公交搜索按钮
    private int isBus = 0;

    private EditText etCity, etSearch;

    private MapView mMapView;

    private BaiduMap mBaiduMap;

    private PoiSearch mPoiSearch;

    private OnGetPoiSearchResultListener listener;

    private String city = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SDKInitializer.initialize(getApplication());

        setContentView(R.layout.activity_poi_search);

        init();

        setCenter();
    }

    /**
     * 初始化activity
     */
    private void init() {
        btnAddr = (Button) findViewById(R.id.btn_addr);
        btnBus = (Button) findViewById(R.id.btn_bus);

        btnAddr.setOnClickListener(this);
        btnBus.setOnClickListener(this);

        etCity = (EditText) findViewById(R.id.et_city);
        etSearch = (EditText) findViewById(R.id.et_search);

        mMapView = (MapView) findViewById(R.id.mv1);

        mBaiduMap = mMapView.getMap();

        mPoiSearch = PoiSearch.newInstance();

        listener = new OnGetPoiSearchResultListener() {

            private BusLineSearch mBuslineSearch;

            private OnGetBusLineSearchResultListener BusListener = new OnGetBusLineSearchResultListener() {
                @Override
                public void onGetBusLineResult(BusLineResult busLineResult) {
                    // 判断，如果有结果就把结果展示在地图上
                    if (busLineResult == null
                            || busLineResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
                        Toast.makeText(PoiSearchActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (busLineResult.error == SearchResult.ERRORNO.NO_ERROR) {
                        BusLineOverlay overlay = new BusLineOverlay(
                                mBaiduMap);
                        mBaiduMap.setOnMarkerClickListener(overlay);
                        overlay.setData(busLineResult);
                        overlay.addToMap();
                        overlay.zoomToSpan();
                    }
                }
            };

            @Override
            public void onGetPoiResult(PoiResult poiResult) {
                if (poiResult == null ||
                        poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
                    Toast.makeText(PoiSearchActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
                    return;
                }
                String busLineUid = null;
                if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
                    if (isBus == 1) {
                        for (PoiInfo info : poiResult.getAllPoi()) {
                            if (info.type == PoiInfo.POITYPE.BUS_LINE ||
                                    info.type == PoiInfo.POITYPE.SUBWAY_LINE) {
                                busLineUid = info.uid;
                            }
                        }
                        if (busLineUid != null) {
                            mBuslineSearch = BusLineSearch.newInstance();

                            mBuslineSearch.setOnGetBusLineSearchResultListener(BusListener);

                            mBuslineSearch.searchBusLine(new BusLineSearchOption().city(city).uid(busLineUid));
                        }

                    } else if (isBus == 0) {

                        mBaiduMap.clear();

                        MyPoiOverlay poiOverlay = new MyPoiOverlay(mBaiduMap);
                        mBaiduMap.setOnMarkerClickListener(poiOverlay);
                        poiOverlay.setData(poiResult);

                        poiOverlay.addToMap();
                        poiOverlay.zoomToSpan();
                    }
                }
            }

            @Override
            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {
                if (poiDetailResult == null ||
                        poiDetailResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
                    Toast.makeText(PoiSearchActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (poiDetailResult.error == SearchResult.ERRORNO.NO_ERROR) {
                    mBaiduMap.hideInfoWindow();

                    String msg = "地址:" + poiDetailResult.getAddress() +
                            "\n店名:" + poiDetailResult.getName() +
                            "\n电话:" + poiDetailResult.getTelephone();

                    Button button = new Button(getApplication());
                    button.setText(msg);
                    button.setGravity(Gravity.LEFT);
                    button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                    button.setTextColor(0xff000000);
                    button.setBackgroundResource(R.drawable.popup_left);
                    InfoWindow infoWindow = new InfoWindow(button,
                            poiDetailResult.getLocation(),
                            -47);

                    mBaiduMap.showInfoWindow(infoWindow);
                }
            }

        };

        mPoiSearch.setOnGetPoiSearchResultListener(listener);
    }

    /**
     * 地点检索
     */
    private void clickSearchAddr() {
        String city = etCity.getText().toString();
        String search = etSearch.getText().toString();

        if ("".equals(city) || "".equals(search))
            return;

        mPoiSearch.searchInCity(new PoiCitySearchOption().city(city).keyword(search).pageNum(10));
    }

    /**
     * 公交检索
     */
    private void clickSearchBus() {
        city = etCity.getText().toString();
        String search = etSearch.getText().toString();

        if ("".equals(city) || "".equals(search))
            return;

        mPoiSearch.searchInCity(new PoiCitySearchOption().city(city).keyword(search));

    }

    // 设置中心点,和缩放等级
    private void setCenter() {
        LatLng position = new LatLng(23.090035, 113.302216);
        MapStatusUpdate center = MapStatusUpdateFactory.newLatLng(position);
        mBaiduMap.setMapStatus(center);

        // 设置缩放等级
        MapStatusUpdate zoom = MapStatusUpdateFactory.zoomTo(15);
        mBaiduMap.setMapStatus(zoom);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_addr:
                isBus = 0;
                clickSearchAddr();
                break;
            case R.id.btn_bus:
                isBus = 1;
                clickSearchBus();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        mPoiSearch.destroy();
    }

    class MyPoiOverlay extends PoiOverlay {

        /**
         * 构造函数
         *
         * @param baiduMap 该 PoiOverlay 引用的 BaiduMap 对象
         */
        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int i) {
            super.onPoiClick(i);

            PoiInfo poiInfo = getPoiResult().getAllPoi().get(i);
            mPoiSearch.searchPoiDetail(new PoiDetailSearchOption().poiUid(poiInfo.uid));
            return true;
        }
    }
}
